package com.ysh.webflux.service.impl;

import com.ysh.webflux.pojo.User;
import com.ysh.webflux.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 袁胜虎 on 2022/9/22 11:36
 */
@Service
public class UserServiceImpl implements UserService {
    //创建 map 集合存储数据
    private final Map<Integer,User> users = new HashMap<>();

    public UserServiceImpl() {
        this.users.put(1,new User("lucy","female",20));
        this.users.put(2,new User("mary","female",25));
        this.users.put(3,new User("jack","male",30));
    }
    //根据 id 查询
    @Override
    public Mono<User> getUserById(int id) {
        return Mono.justOrEmpty(this.users.get(id));
    }

    @Override
    public Flux<User> getAllUser() {
        return Flux.fromIterable(this.users.values());
    }

    @Override
    public Mono<Void> saveUserInfo(Mono<User> userMono) {
        return userMono.doOnNext(person->{
            int id = users.size()+1;
            users.put(id,person);
        }).thenEmpty(Mono.empty());
    }

    @Override
    public Flux<User> getUsersStream() {
        return Flux.fromIterable(this.users.values()).doOnNext(user -> {
            try {
                Thread.sleep(50000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public User getUserById1(int id) {
        return users.get(id);
    }

    @Override
    public List<User> getAllUser1() {
        return users.values().stream().collect(Collectors.toList());
    }

    @Override
    public void saveUserInfo1(User user) {

        users.put(users.size()+1,user);
    }

}
